import type { ProDescriptionsItemProps } from '@/components/ProDescriptions';
import ProDescriptions from '@/components/ProDescriptions';
import React, { useEffect, useState } from 'react';
import type { Tenant, TenantDetailItem } from '../data';
import { Tag } from 'antd';
import AdminAccessConfiguration from './AdminRolesConfiguration';

import { editTenantRoles, queryTenantDetail } from '../service';

export interface TenantDetailProps {
  tenant: Tenant;
}

const TenantDetailView: React.FC<TenantDetailProps> = (props) => {

  const [ data, setData ] = useState<TenantDetailItem>({ ...props.tenant });

  useEffect(() => {
    queryTenantDetail({ id: props.tenant.id }).then((res) => {
      setData(res.data || props.tenant);
    });

  }, [ props.tenant.id ]);

  const columns: ProDescriptionsItemProps<TenantDetailItem>[] = [
    {
      label: '客户编号',
      dataIndex: 'id',
    },
    {
      label: '客户名',
      dataIndex: 'name',
      editable: true,
      onSubmit: async (value: string) => {
        setData({ ...data, name: value });
        const res = await editTenantRoles({ id: tenant.id, name: value });
        return res.code === 0;
      },
    },
    {
      label: 'AccessKey',
      dataIndex: 'accessKey',
    },
    {
      label: 'SecretKey',
      dataIndex: 'secretKey',
    },
    {
      label: '拥有角色',
      dataIndex: 'roles',
      editable: true,
      render: (_, record) => record?.roles?.map((item) => <Tag key={ item.id }>{ item.name }</Tag>),
      renderEdit: (_, { value, onChange }) => (
        <AdminAccessConfiguration
          defaultValue={ value }
          id={ props.tenant.id }
          onChange={ (values) => onChange && onChange(values) }
        />
      ),
      onSubmit: async (val) => {
        const res = await editTenantRoles({ id: props.tenant.id, roles: val });
        return res.code === 0;
      },
    },
  ];

  return (
    <ProDescriptions
      title='客户详情'
      column={ 1 }
      initData={ data }
      columns={ columns }
    />
  );
};
export default TenantDetailView;
